package server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;

import org.apache.log4j.Logger;

public class CloudKeeperServer2 extends Thread {
	private static final Logger logger = Logger.getLogger(CloudKeeperServer2.class);

	private Selector selector;
	private ServerSocketChannel serverSocketChannel;

	public CloudKeeperServer2(int port) throws IOException {
		this.selector = Selector.open();
		this.serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
		start();
	}

	public void run() {
		logger.error("start...");
		while (!serverSocketChannel.socket().isClosed()) {
			try {
				selector.select(1000);
				Set<SelectionKey> s_selectionKey;
				synchronized (this) {
					s_selectionKey = selector.selectedKeys();
				}
				ArrayList<SelectionKey> l_selectionKey = new ArrayList<SelectionKey>(s_selectionKey);
				Collections.shuffle(l_selectionKey);
				for (SelectionKey selectionKey : l_selectionKey) {
					if ((selectionKey.readyOps() & SelectionKey.OP_ACCEPT) != 0) {
						SocketChannel socketChannel = ((ServerSocketChannel) selectionKey.channel()).accept();
						socketChannel.configureBlocking(false);
						socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
						logger.error("连接上了！");
					} else if ((selectionKey.readyOps() & SelectionKey.OP_READ) != 0) {
						SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
						ByteBuffer byteBuffer = ByteBuffer.allocate(4);
						int rc = socketChannel.read(byteBuffer);
						if (rc != -1) {
							byteBuffer.flip();
							logger.error(byteBuffer.getInt());
						}
					} else if ((selectionKey.readyOps() & SelectionKey.OP_WRITE) != 0) {
						
					}
				}
				s_selectionKey.clear();
			} catch (Exception e) {
				logger.error("error : " + e, e);
			}
		}
		logger.error("end...");
	}

	public static void main(String[] args) throws IOException {
		new CloudKeeperServer2(10055);
	}
}